package com.qf.blog.controller;

import com.alibaba.fastjson.JSON;
import com.qf.blog.commons.response.ResponseResult;
import com.qf.blog.service.IUserService;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@RequestMapping("/file")
@Controller
public class FileUplaodController {
    @Autowired
    private UploadManager uploadManager;
    @Autowired
    private IUserService iUserService;

    @Value("${blog.qiniuyun.ak}")
    private String ak;

    @Value("${blog.qiniuyun.sk}")
    private String sk;

    @Value("${blog.qiniuyun.bucket}")
    private String bucket;

    @Value("${blog.qiniuyun.host}")
    private String host;


    @RequestMapping("/upload")
    @ResponseBody
    public ResponseResult upload(MultipartFile file) {
        // 1、文件名称
        String key = file.getOriginalFilename();
        // 2.认证
        Auth auth = Auth.create(ak, sk);
        // 3.获取token
        String upToken = auth.uploadToken(bucket, key);
        // 4.上传
        String path = null;
        try {
            Response response = uploadManager.put(file.getInputStream(), key, upToken, null, null);
            DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            path = host + defaultPutRet.key;
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 返回给前端
        return ResponseResult.success(path);
    }
}
